/**
 * Description:
 * Class Name:ExecuteDDL
 * Date:2022/4/4 15:23
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_4_执行SQL语句的方式._13_4_1_使用executeUpdate方法来执行DDL和DML语句;

import java.io.FileInputStream;
import java.util.Properties;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;

public class ExecuteDDL {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFile) throws Exception {
        // 使用Properties类来加载ini属性文件
        var props = new Properties();
        props.load(new FileInputStream(paramFile));

        // 从加载好的属性文件中获得对应的字典值
        driver = props.getProperty("driver", "com.mysql.cj.jdbc.Driver");
        url = props.getProperty("url");
        user = props.getProperty("user", "root");
        pwd = props.getProperty("pwd", "123456");
    }

    public void createTable(String sql) throws Exception{
        // 加载驱动
        Class.forName(driver);
        // 进行连接，并获取连接对象
        try (
                Connection connection = DriverManager.getConnection(url, user, pwd);
                Statement statement = connection.createStatement();
        ){
            // 执行DDL语句，这里先用try来粗糙地约束传入的语句只能是DDL、DML语句，否则报错
            statement.executeUpdate(sql);
        }
    }

    public static void main(String[] args) throws Exception{
        var ed = new ExecuteDDL();
        /*
        这句因为暂时不熟悉Java中的运行时路径获取机制，只能暂时使用绝对路径了，当然最可靠的是因该加入到CLASSPATH中
         */
        ed.initParam("Chapter_13_mysql.ini");

        String temp_sql = "create table jdbc_test(" +
                "jdbc_id int auto_increment primary key," +
                "jdbc_name varchar(255)," +
                "jdbc_desc text" +
                ");";
        ed.createTable(temp_sql);
        System.out.println("create success!");
    }
}
